<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import { ElMessage, type FormInstance, ElCard, ElButton, ElTag, ElMenu, ElMenuItem, ElContainer, ElAside, ElMain } from 'element-plus'
import { User, Lock, Key, Coffee, Clock, Calendar, View, Document, Link ,VideoCamera } from '@element-plus/icons-vue'
import type { Course } from '@/types/course.ts'
import { useAuthStore } from "@/stores/auth.ts"
import PdfViewer from '@/views/emp/PDFResource.vue'
import { useRouter } from "vue-router"
import axios from "@/utils/request.ts"
import { useRoute } from 'vue-router'
import type { CourseResource } from '@/types/resourse.ts'

const route = useRoute()

// 静态资源访问前缀
const STATIC_PREFIX = 'http://localhost:8080/static/documents/'

// 资源数据
const resourses = ref<CourseResource[]>([])
// 当前选中的资源ID
const activeResourceId = ref<number | null>(null)

// 获取当前选中的资源
const activeResource = computed(() => {
  return resourses.value.find(r => r.id === activeResourceId.value) || null
})

// 添加资源加载状态标记
const resourcesLoaded = ref(false)

// 修改获取资源列表的方法，添加加载完成标记
const getAllResourseByEmp = () => {
  // 重置状态
  resourcesLoaded.value = false
  activeResourceId.value = null

  axios.get("/courseResource/selectResourseByCourseId", {
    params: { courseId: route.params.courseId }
  }).then(res => {
    console.log(res.data.resourses)
    resourses.value = res.data.resourses
    // 如果有资源，默认选中第一个
    if (res.data.resourses.length > 0) {
      activeResourceId.value = res.data.resourses[0].id
    }
    // 标记数据加载完成
    resourcesLoaded.value = true
  }).catch(err => {
    ElMessage.error('获取资源列表失败')
    console.error(err)
    // 即使失败也标记加载完成（避免一直处于加载状态）
    resourcesLoaded.value = true
  })
}

// 切换资源
const handleResourceChange = (resourceId: string) => {
  activeResourceId.value = parseInt(resourceId)
}

onMounted(() => {
  getAllResourseByEmp()
})

// 获取资源图标
const getResourceIcon = (resource: CourseResource) => {
  const trainingResource = resource.trainingResource
  if (!trainingResource) return Document
  if (trainingResource.isDocument) return Document
  if (trainingResource.resourceUrl?.includes('video') || trainingResource.isSpeed) return VideoCamera
  return Link
}

// PDF下载成功回调
const handlePdfDownloadSuccess = () => {
  ElMessage.success('PDF下载成功')
}

// PDF下载失败回调
const handlePdfDownloadFail = (error: Error) => {
  ElMessage.error('PDF下载失败')
  console.error('PDF下载错误:', error)
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<template>
  <el-container style="height: 100vh; border: 1px solid #eee;">
    <!-- 左侧菜单栏 -->
    <el-aside width="250px" style="background-color: #f5f7fa; border-right: 1px solid #eee;">
      <div style="padding: 16px; border-bottom: 1px solid #eee;">
        <h2 style="margin: 0; font-size: 16px;">课程资源列表</h2>
      </div>
      <el-menu
          default-active="0"
          class="el-menu-vertical-demo"
          @select="handleResourceChange"
          background-color="#f5f7fa"
          text-color="#333"
          active-text-color="#409EFF"
      >
        <el-menu-item
            v-for="(resource, index) in resourses"
            :key="resource.id"
            :index="resource.id.toString()"
        >
          <template #icon>
            <component :is="getResourceIcon(resource)" />
          </template>
          <span>
            {{ index + 1 }}. {{ resource.trainingResource?.resourceName || '未命名资源' }}
          </span>
          <el-tag
              v-if="!resource.trainingResource?.isDocument"
              size="small"
              style="margin-left: 8px;"
          >
            文档
          </el-tag>
          <el-tag
              v-if="resource.trainingResource?.isDocument"
              size="small"
              type="success"
              style="margin-left: 8px;"
          >
            视频
          </el-tag>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区 -->
    <el-main style="padding: 20px;">
      <el-card>
        <div slot="header">
          <h1 style="margin: 0;">资源详情</h1>
        </div>
        <div v-if="activeResource">
          <div class="resource-detail">
            <div class="resource-header">
              <h2 class="resource-title">{{ activeResource.trainingResource?.resourceName || '未命名资源' }}</h2>
            </div>
            <div class="resource-info">
              <h3>资源信息</h3>
              <div class="info-grid">
                <div class="info-item">
                  <span class="info-label">资源类型:</span>
                  <span class="info-value">
                    {{ !activeResource.trainingResource?.isDocument ? '文档' : '视频' }}
                  </span>
                </div>
                <div class="info-item" v-if="activeResource.trainingResource?.isDocument">
                  <span class="info-label">是否支持倍速:</span>
                  <span class="info-value">
                    {{ activeResource.trainingResource?.isSpeed ? '是' : '否' }}
                  </span>
                </div>
                <div class="info-item" v-if="activeResource.trainingResource?.isDocument">
                  <span class="info-label">资源时长:</span>
                  <span class="info-value">
                    {{ activeResource.trainingResource?.resourceTotalDuration || '0' }} 秒
                  </span>
                </div>
              </div>
            </div>

            <div class="resource-description">
              <h3>资源描述</h3>
              <p>{{ activeResource.trainingResource?.resourceDesc || '无描述信息' }}</p>
            </div>

            <!-- 文档PDF区域 -->
            <div class="resource-url" v-show="!activeResource.trainingResource?.isDocument">
              <h3>文档pdf</h3>
              <div class="url-display">{{ STATIC_PREFIX + (activeResource.trainingResource?.resourceUrl || '无路径信息') }}</div>
              <div style="margin-top: 16px;">
                <!-- 只有当资源加载完成且存在有效PDF地址时才渲染PDF组件 -->
                <PdfViewer
                    v-if="resourcesLoaded && activeResource?.trainingResource?.resourceUrl"
                    :pdf-url="STATIC_PREFIX + (activeResource.trainingResource?.resourceUrl || '')"
                    :file-name="activeResource.trainingResource?.resourceName || '文档'"
                    height="700px"
                    @download-success="handlePdfDownloadSuccess"
                    @download-fail="handlePdfDownloadFail"
                />
                <!-- 加载状态提示 -->
                <div v-else-if="resourcesLoaded && !activeResource?.trainingResource?.resourceUrl">
                  <p>该资源没有有效的PDF文件路径</p>
                </div>
              </div>
            </div>

            <!-- 视频区域 -->
            <div class="resource-url" v-if="activeResource.trainingResource?.isDocument">
              <h3>视频播放器显示区域</h3>
              <div class="url-display">{{ STATIC_PREFIX + (activeResource.trainingResource?.resourceUrl || '无路径信息') }}</div>



            </div>

            <div class="resource-actions" style="margin-top: 20px;">
              <el-button type="primary" :icon="!activeResource.trainingResource?.isDocument ? Document : VideoCamera">
                {{ !activeResource.trainingResource?.isDocument ? '查看文档' : '播放视频' }}
              </el-button>
            </div>
          </div>
        </div>
        <div v-else>
          <p>请从左侧选择一个资源</p>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<style scoped>
.el-container {
  overflow: hidden;
}

.el-aside {
  overflow-y: auto;
}

.el-menu-vertical-demo {
  border-right: none;
}

::v-deep .el-menu-item {
  height: 50px;
  line-height: 50px;
}

.resource-detail {
  padding: 10px 0;
}

.resource-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.resource-title {
  margin: 0 0 15px 0;
  font-size: 20px;
  color: #333;
}

.resource-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.resource-info {
  margin-bottom: 20px;
}

.resource-info h3,
.resource-description h3,
.resource-url h3 {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
}

.info-label {
  width: 100px;
  color: #666;
  font-weight: 500;
}

.info-value {
  flex: 1;
  color: #333;
}

.resource-description p {
  line-height: 1.6;
  color: #333;
  margin: 0;
}

.resource-url {
  margin: 20px 0;
}

.url-display {
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
  word-break: break-all;
  color: #666;
}
</style>